const { log } = require("console");
const zlib = require("zlib");

class SizePlugin {
  apply(compiler) {
    compiler.hooks.done.tap("SizePlugin", (stats) => {
      const assets = stats.toJson().assets;
      console.log("File\t\t\t\tSize\t\tGzip Size");
      console.log("----------------------------------");
      assets.forEach((asset) => {
        // console.log("asset=", asset);
        const filename = asset.name.padEnd(16);
        const size = formatBytes(asset.size).padEnd(10);
        // const gzipped = formatBytes(zlib.gzipSync(asset.source()).length);
        const gzipped = formatBytes(asset.size);
        console.log(`${filename}\t\t${size}\t${gzipped}`);
      });
      console.log("----------------------------------");
    });
  }
}

function formatBytes(bytes, decimals = 2) {
  if (bytes === 0) return "0 Bytes";
  const k = 1024;
  const dm = decimals < 0 ? 0 : decimals;
  const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + " " + sizes[i];
}

module.exports = SizePlugin;
